package com.example.tcp.server.jt808;

import com.example.tcp.server.Client;
import com.example.tcp.server.Frame;
import com.example.tcp.server.example.ExampleClient;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AsciiString;

import java.util.function.Function;


public class Jt808Frame extends Frame {

    public Jt808Frame(ByteBuf data) {
        super(data);
    }

    @Override
    public Client getClient(ChannelHandlerContext ctx) {

        if(this.content().getUnsignedByte(0) != 0x7e) {
            return null;
        }

        StringBuilder temp = new StringBuilder(12);
        this.content().slice(0, 6).forEachByte(b -> {
            temp.append((byte) ((b & 0xf0) >>> 4));
            temp.append((byte) (b & 0x0f));
            return true;
        });
        AsciiString deviceId = AsciiString.cached(temp.toString());
        return Client.getOrCreateClient(deviceId, ctx.channel(), new Function<AsciiString, Client>() {
            @Override
            public Client apply(AsciiString key) {
                return new Jt808Client(key, ctx.channel());
            }
        });
    }
}
